/*
 * @Descripttion: 简要描述
 * @Author: ZIQin Zhai
 * @Date: 2020-02-03 14:36:13
 * @LastEditors: qinyonglian
 * @LastEditTime: 2021-09-28 11:09:30
 */

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

/**
 * 代理服务
 */
const express = require('express');
const request = require('request');
const path = require('path'); // 系统路径模块
const fs = require('fs'); // 文件模块
const chalk = require('chalk');// 控制台输出颜色
const utils = require('../webpack/util');

// 配置信息
const config = require('../config.js');

const app = express();

// 静态资源,没有代理走路由
const statics = [
  { router: '/index.html' },
  { router: '/config' },
  { router: '/public' },
  // { router: '/static' },
  { router: '/appStatic' },
  { router: '/js' },
  { router: '/lib' },
  { router: '/view' },
];

const mapping = utils.createPluginNameMapping();

// 本地测试数据
const datas = [
  { router: '/config/config.json' },
];
datas.map((item) => {
  app.use(item.router, (req, res) => {
    const url = req.originalUrl.split('?')[0];
    const file = path.join(__dirname, url); // 文件路径，__dirname为当前运行js文件的目录
    // 读取json文件
    fs.readFile(file, 'utf-8', (err, data) => {
      if (err) {
        res.send('{success:false,obj:"文件读取失败"}');
      } else {
        res.send(data);
      }
    });
  });
});

statics.map((item) => {
  app.use(item.router, express.static(path.resolve(__dirname, '../../', `.${item.proxy || item.router}`)));
});

// 路由代理
const { proxyServerUrl } = config;
const { serverUrl } = config;
const rbacUrl = config.proxyRbacUrl;
const routers = [
  { router: '/rbac', folder: 'RBAC', proxy: proxyServerUrl }, // 登录rbac
  { router: '/je', folder: 'SERVER', proxy: serverUrl }, // 数据请求
  { router: '/app', folder: '本地插件调试', proxy: '/' }, // 数据请求
  { router: '/dev', folder: 'H5环境服务代理', proxy: proxyServerUrl }, // 数据请求
  { router: '', folder: '线上应用', proxy: `${serverUrl}` }, // 数据请求
];
routers.map((item) => {
  if (item.proxy) {
    const _router = item.router; // 路由
    const { folder } = item; // 目录描述
    const { proxy } = item; // 代理
    app.use(_router, (req, res, next) => {
      let url = proxy + _router + req.url;
      if (req.originalUrl.startsWith('/static/ux/je/je.min.js')) {
        request(url, (err, response, body) => {
          if (!err && response.statusCode == 200) {
            body += [
              ';\n',
              `JE.pluginUtil.rewrite = function() {
                JE.pluginUtil.getRuntimePublicPath = function(pluginCode){
                  let pluginConfigs = ${JSON.stringify(utils.entryConfigs)};\n
                  let pluginInfo = (pluginConfigs||{})[pluginCode] || {};\n
                  return pluginInfo.debug ? '/app/' : JE.pluginFullPath
                };
              };\n`,
            ].join('');
            res.send(body);
          }
        });
      } else {
        let ext = req.url.split('.');
        ext = ext[ext.length - 1];
        if (_router === '/app') {
          const apps = req.url.split('.');
          const contents = apps[0].split('/'); // 目录层级
          const appName = contents[1];
          let ext = apps[apps.length - 1];
          if (ext === 'map') {
            next();
            return;
          }
          // 文件的hash编码
          const hashCode = apps.slice(1, apps.length - 1);
          hashCode.length > 0 && (hashCode.unshift(''));
          const pluginConfigPath = `./src/app/views/${mapping[appName]}/config.json`;
          const pluginConfig = utils.getConfig(pluginConfigPath);

          if (pluginConfig && pluginConfig.debug) {
            ext = ext.split('?');
            ext = ext[0];
            // 子路由的路径是由webpack生成，直接访问即可
            if (contents.length > 3) {
              url = `http://localhost:${config.serverPort}/appStatic/${contents.slice(1).join('/')}${hashCode.join('.')}.${ext}`;
            } else if (['js', 'css'].includes(ext)) {
              url = `http://localhost:${config.serverPort}/appStatic/${pluginConfig[ext === 'js' ? 'jsEntry' : 'cssEntry']}`;
            } else {
              url = `http://localhost:${config.serverPort}/appStatic/${url}`;
            }
            console.log(chalk.gray(`[${folder}] ${proxy}`) + url);
          }
          req.pipe(request(url)).pipe(res);
        } else if (_router == '/dev') {
          url = `${proxy}/${req.url}`;
          console.log(chalk.gray(`[${folder}] ${proxy}`) + req.url);
          req.pipe(request(url)).pipe(res);
        } else if (_router == '/je' || _router == '/rbac') {
          url = `${proxyServerUrl}${_router}${req.url}`;
          console.log(chalk.gray(`[${folder}] ${proxy}`) + req.url);
          req.pipe(request(url)).pipe(res);
        } else if (_router == '/' || req.baseUrl == _router) {
          if (ext === 'map') {
            next();
          } else {
            console.log(chalk.gray(`[${folder}] ${proxy}`) + _router + req.url);
            req.pipe(request(url)).pipe(res);
          }
        } else {
          next();
        }
      }
    });
  }
});

// 启动服务
app.listen(config.serverPort, config.server, () => { // 前端ajax地址写 http://localhost:3000/
  console.log('');
  console.log(`本地服务已启动，请访问：${chalk.green(`${config.server}:${config.serverPort}`)}`);
  console.log('');
});
